package com.aboverock.module.shiro.realms;

import java.util.Collection;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class MyModularRealmAuthenticator.
 *
 * @author Rock Wang
 */
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

    private static final Logger logger = LoggerFactory.getLogger(MyModularRealmAuthenticator.class);

    @Override
    protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
        AuthenticationStrategy strategy = getAuthenticationStrategy();

        AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);

        if (logger.isTraceEnabled()) {
            logger.trace("Iterating through {} realms for PAM authentication", realms.size());
        }

        for (Realm realm : realms) {

            aggregate = strategy.beforeAttempt(realm, token, aggregate);

            if (realm.supports(token)) {

                logger.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);

                AuthenticationInfo info = null;
                Throwable t = null;
                try {
                    info = realm.getAuthenticationInfo(token);
                } catch (Throwable throwable) {
                    t = throwable;
                    if (logger.isDebugEnabled()) {
                        // String msg = "Realm [" + realm
                        // + "] threw an exception during a multi-realm authentication attempt:";
                        // log.debug(msg, t);
                        logger.debug(
                                "Data-Smart: Realm [{}] threw an exception during a multi-realm authentication attempt:{}",
                                realm, t.getMessage());
                    }
                }
                // 如果用户锁定，直接跳出认证
                if (t != null && t.getClass().equals(LockedAccountException.class)) {
                    throw new LockedAccountException(t);
                }
                // 有一个Realm认证成功，即停止后续认证
                aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
                if (aggregate != null && 1 == aggregate.getPrincipals().getRealmNames().size()) {
                    break;
                }

            } else {
                logger.debug("Data-Smart: Realm [{}] does not support token {}. Skipping realm.", realm, token);
            }
        }

        // aggregate = strategy.afterAllAttempts(token, aggregate);

        return aggregate;
    }
}
